package tool.workflow.soft

import java.io.{File, FileOutputStream}
import command.CommandExec
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import shared.Pojo._
import tool.{FormTool, Pojo, Tool, XlsxStyle}
import tool.workflow.soft.AllSubSoft.SubSoftBT
import utils.Utils
import implicits.Implicits._
import shared.SharedTool
import tool.Pojo._
import upickle.default._
import com.softwaremill.quicklens._

/**
 * Created by yz on 30/10/2020
 */
object NaIdentify extends SubSoftBT with NaIdentifySoftT {

  override def exec(workspaceDir: File, resultDir: File, si: String): CommandExec[Any, Boolean] = {
    CommandExec().exec { b =>
      getCommandData(workspaceDir, resultDir, si)
    }.map { b =>
      execAfterCommand(workspaceDir, resultDir, si)
    }
  }

  override def getCommand(si: String): String = {
    s"""
       |${"Rscript".condaPath()} ${Tool.rPath.unixPath}/na_identify.R --si "${si}"
                       """.stripMargin
  }

  override def getCommandData(workspaceDir: File, resultDir: File, si: String): CommandData = {
    val command = getCommand(si)
    CommandData(workspaceDir, List(command))
  }

  override def execAfterCommand(workspaceDir: File, resultDir: File, si: String): Unit = {
    super.execAfterCommand(workspaceDir, resultDir, si)
    naIdentify(workspaceDir, resultDir, si)
  }

  def naIdentify(workspaceDir: File, resultDir: File, si: String) = {
    val value = Utils.configFile2JsonByFile(Tool.getColorJsonFile(workspaceDir))
    val data =value.transform(reader[NaIdentifyColorData])
    val step = si.mySplit(";")(0)
    val file = new File(workspaceDir, s"${step}.result.txt")
    val outFile = new File(workspaceDir, s"${step}.na_identify.xlsx")
    val color = data.naColors(step.toInt-1)
    naIdentifyExec(file, outFile, color)
  }

  def naIdentifyExec(inputFile: File, outFile: File, color: String) = {
    val outputWorkbook = new XSSFWorkbook()
    val outputSheet = outputWorkbook.createSheet("Sheet1")
    val format = outputWorkbook.createDataFormat()
    val lines = inputFile.txtLines
    val xlsxStyle = new XlsxStyle(outputWorkbook)
    val cellStyle = xlsxStyle.customStyle(color)
    for (i <- 0 until lines.size) {
      val outputEachRow = outputSheet.createRow(i)
      val columns = lines(i)
      for (j <- 0 until columns.size) {
        val cell = outputEachRow.createCell(j)
        cell.setCellValue(columns(j))
        if (i > 0 && j > 0) {
          val v = columns(j)
          if (columns(j).isDouble) {
            cell.setCellValue(columns(j).toDouble)
          }
          if (!v.isDouble || v.toDouble == 0) {
            cell.setCellStyle(cellStyle)
          }
        }
      }
    }
    val fileOutputStream = new FileOutputStream(outFile)
    outputWorkbook.write(fileOutputStream)
    fileOutputStream.close()
    outputWorkbook.close()
  }

}
